<?php

class DispatchboardController extends Controller {

    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            array(
                'application.filters.RequireLoginFilter',
            ),
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }
	
	public function actionCreate()
	{
	
	}
	
    public function actionGetData($boardid=NULL){
        echo $this->renderPartial('_board',array(
            'statusList'=>$this->getStatusList($boardid),
            'employeeList'=>$this->getEmployeeList($boardid)
        ),true);
    }
    protected function getStatusList($boardid=null){
      
               
        $rs=array();
        $boardEmployeeCrit = new CDbCriteria();
        $boardEmployeeCrit->alias = 'e';
        $boardEmployeeCrit->join = 'left join tbl_dispatchboard_assignments ba on ba.empno=e.empno';
        if($boardid!=null){
            $boardEmployeeCrit->compare('ba.dispatchboardid',$boardid);
            $boardEmployeeCrit->compare('ba.side','L');
            $boardEmployeeCrit->addCondition('lower(e.unassign)="y"','or');
        }else{
            $boardEmployeeCrit->addCondition('lower(e.unassign)="y"');    
        }
        
        $boardEmployeeCrit->order = 'e.unassign desc';
        $boardEmployees = Employees::model()->findAll($boardEmployeeCrit);
        foreach($boardEmployees as $emp){
            $rs[$emp->empno]=array();
            $rs[$emp->empno]['data']=array();
            $rs[$emp->empno]['employeename']=$emp->firstname.' '.$emp->lastname;
            $rs[$emp->empno]['empno']=$emp->empno;

            $techCrit        = new CDbCriteria();
            $techCrit->alias = 't';
            $techCrit->join  = 'left join tbl_dispatchdetails d on t.dispatch=d.dispatch
                    left join tbl_employees e on t.empno=e.empno
                    left join tbl_dispatchboard_assignments ba on ba.empno=e.empno
                    ';
            $techCrit->addCondition('d.complete is null AND t.enddate is NULL AND t.endtime is NULL');
            //$techCrit->addCondition('lower(e.unassign)="y"');
            if($boardid!=null){
                $techCrit->addCondition('(ba.dispatchboardid =:boardid and ba.side="L") or lower(e.unassign)="y"');
                $techCrit->params = array('boardid'=>$boardid);
                
            }
            $techCrit->compare('e.empno',$emp->empno);
            $techList = DispatchTech::model()->findAll($techCrit); 

            foreach($techList as $i=>$tech){
                $rs[$tech->empno]['data'][$i]=$tech;
                $rs[$tech->empno]['employeename']=$tech->employee->firstname.' '.$tech->employee->lastname;
                $rs[$tech->empno]['empno']=$tech->empno;
            }
        }


        // $boardEmployeeCrit = new CDbCriteria();
        // $boardEmployeeCrit->alias = 'e';
        // $boardEmployeeCrit->join = 'left join tbl_dispatchboard_assignments ba on ba.empno=e.empno';
        // if($boardid!=null){
        //     $boardEmployeeCrit->compare('ba.dispatchboardid',$boardid);
        //     $boardEmployeeCrit->compare('ba.side','L');
        // }
        // $boardEmployees = Employees::model()->findAll($boardEmployeeCrit);
        // $rs['boardEmployees']=$boardEmployees
        return $rs;
    }

    public function getEmployeeList($boardid=NULL){
        //echo json_encode($list1);
        Yii::app()->request->cookies['lastBoardId'] = new CHttpCookie('lastBoardId',$boardid);
        $employeeCrit = new CDbCriteria();
        $employeeCrit->alias = 'e';
        $employeeCrit->join = 'left join tbl_dispatchboard_assignments ba on ba.empno=e.empno';
        $employeeCrit->compare('e.status',1);
        if($boardid!=null){
            $employeeCrit->compare('ba.dispatchboardid',$boardid);
            $employeeCrit->compare('ba.side','R');        
        }else{

        }
        $employeeCrit->order = 'e.unassign desc';

      
        $allEmp=Employees::model()->findAll($employeeCrit);
        
        $list2=array();
        foreach($allEmp as $item){
         
            $i=0;
            
            $list2[$item['empno']]['data']=array();
            $list2[$item['empno']]['name']=$item->firstname.' '.$item->lastname;

            $techCrit = new CDbCriteria();
            $techCrit->alias = 't';
            $techCrit->select = 'distinct t.*';
            $techCrit->join = '
                left join tbl_dispatchdetails d on t.dispatch=d.dispatch
                left join tbl_employees e on t.empno=e.empno
                left join tbl_dispatchboard_assignments ba on ba.empno=e.empno';

            $techCrit->addCondition('d.complete is null AND t.enddate is NULL AND t.endtime is NULL');
            
            if($boardid!=null){
                $techCrit->compare('ba.dispatchboardid',$boardid);
                $techCrit->compare('ba.side','R');
            }
            $techCrit->compare('e.empno',$item->empno);
            $techList = DispatchTech::model()->findAll($techCrit); 
            //echo count($techList);exit;
            foreach ($techList as $index=>$tech){                                               
         
                $list2[$item->empno]['data'][$index]=$tech;    

            }
        }
      
        return $list2;
    }
    public function actionIndex(){
        if(isset(Yii::app()->request->cookies['lastBoardId'])){
            $boardid = Yii::app()->request->cookies['lastBoardId']->value;
        }else{
            $boardid = null;
        }
        $this->render('index',array(
            'lastBoardId'=>$boardid,
            'statusList'=>$this->getStatusList($boardid),
            'employeeList'=>$this->getEmployeeList($boardid)
        ));
    }
	
	 public function actionGetDispatchBoardList($page=1, $sort=NULL, $dir=NULL) {
        //we decrease $page by 1 because in Extjs first page is 1, but in our sql first page is 0;
        if ($page > 0)
            $page--;

        $vendors = new CActiveDataProvider('DispatchBoard', array(
                    'criteria' => array(
                        'order' => $sort != NULL ? $sort . ' ' . $dir : 'sort',
                    ),
                    'pagination' => array(
                        'pageSize' => 20,
                        'currentPage' => $page,
                    ),
                ));

        $vendorsList = array();
        if ($vendors->getTotalItemCount() > 0) {
            $vendorsList['totalCount'] = $vendors->getTotalItemCount();
            $vendorsList['type'] = 'EmpGroup';
            foreach ($vendors->getData() as $item) {
                $vendorsList['data'][] = $item->getAttributes();
            }
            echo json_encode($vendorsList);
        }
        Yii::app()->end();
    }
	
	public function actionList(){		
        $this->render('list');
    }
	
	 public function loadModel($id) {
        $model = DispatchBoard::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }
	
	 public function actionUpdate($id) {
        if ($id == -1)
            $model = new DispatchBoard();
        else
            $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST)) {
//            $model->attributes = $_POST;
			$model->description = $_POST['description'];
			$model->status = $_POST['status'];
			$model->sort = $_POST['sort'];
            if ($model->save())
                echo 'data saved';
            else
                echo "Create failed: " . json_encode($model->getErrors());
        }
    }

    public function actionAssignToUnassignedEmployee($techid,$empno,$boardid=null){
        $tech=DispatchTech::model()->findByPk($techid);
        if($tech==NULL){
            $this->showAjaxResult('Tech can not be found');
        }
        $emp=Employees::model()->findByPk($empno);
        if($emp==NULL){
            $this->showAjaxResult('Employee can not be found');
        }
        $this->checkDispatchMobile($tech);
        switch($emp->firstname){
            case 'Unassigned':
                $tech->changeStatus('Unassigned',$empno);
            break;
            case 'CC Web/Mob':
                $tech->changeStatus('Unassigned',$empno);
            break;
            case 'Parts':
                $tech->changeStatus('Need Parts');
            break;
            case 'Reassign':
                $tech->changeStatus('Reassign',$empno);
            break;
            case 'IT':
                $tech->changeStatus('IT',$empno);
            break;
        }   
        $this->showAjaxResult('Change status successful',true);
    }

    protected function checkDispatchMobile($tech){
        if($tech->mobile == 1){
            $this->showAjaxResult('Dispatch: '.$tech->dispatchModel->dispatch. ' has been downloaded to a mobile device. To reassign you must contact '
                . $tech->employee->firstname.' ' .$tech->employee->lastname.' at '.$tech->employee->workcell .' to have them reassign it first.');
        }
    }
    public function actionReassignTech($techid,$empno,$boardid = null){
        $tech=DispatchTech::model()->findByPk($techid);
        if($tech==NULL){
            $this->showAjaxResult('Tech can not be found');
        }
        $emp=Employees::model()->findByPk($empno);
        if($emp==NULL){
            $this->showAjaxResult('Employee can not be found');
        }
        $this->checkDispatchMobile($tech);
        if( $tech->changeStatus('Reassign',$empno) == false){
            $this->showAjaxResult('Save failed');            
        }

        
        $data=$this->renderPartial('_board',array(
            'statusList'=>$this->getStatusList($boardid),
            'employeeList'=>$this->getEmployeeList($boardid)
        ), true);
        $this->showAjaxResult($data, true);
    }

    public function actionAssignTech($techid,$empno,$boardid = null){
        $tech=DispatchTech::model()->findByPk($techid);
        if($tech==NULL){
            $this->showAjaxResult('Tech can not be found');
        }
        $emp=Employees::model()->findByPk($empno);
        if($emp==NULL){
            $this->showAjaxResult('Employee can not be found');
        }
        $this->checkDispatchMobile($tech);
        
        if( $tech->changeStatus('Reassign',$empno) == false){
            $this->showAjaxResult('Save failed');            
        }
    
        $data=$this->renderPartial('_board',array(
            'statusList'=>$this->getStatusList($boardid),
            'employeeList'=>$this->getEmployeeList($boardid)
        ), true);
        $this->showAjaxResult($data, true);
        
    }

    public function showAjaxResult($message,$success=false)
    {
        echo json_encode(array(
            'success'=>$success,
            'msg'=>$message
        ));
        Yii::app()->end();
    }

    public function actionGetBoardList()
    {
        $list=DispatchBoard::model()->findAll();
        $rs=array();
        foreach($list as $item){
            $rs['data'][]=$item->attributes;
        }
        $rs['totalCount']=count($list);
        echo json_encode($rs);
    }
    public function actionBoardList(){
        $this->render('boardlist');
    }
    public function actionSubmit(){
        $model=NULL;
        if(isset($_POST['id']) && $_POST['id']!=0){
            
            $model=DispatchBoard::model()->findByPk($_POST['id']);
           
        }else{
            $model=new DispatchBoard;
            
        }
        $model->description=$_POST['description'];
        if($model->save()==false){
            echo json_encode($model->getErrors());
        }
    }
    public function actionDelete($id){
        $board=DispatchBoard::model()->findByPk($id);
        if($board!=NULL){
            $board->delete();
        }
    }
public function actionTest(){
EmailUtil::sendEmail('Dispatch','5025070769@txt.att.net','Assigned Dispatch No $num');
}
}

?>
